package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.Arrays;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-24 16:37:24
 */
public class HotCode016 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        HotCode016 hotCode016 = new HotCode016();
        System.out.println(Arrays.toString(hotCode016.productExceptSelf(nums)));
    }

    public int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return nums;
        }
        int[][] dp = new int[nums.length][2];
        dp[0][0] = 1;
        dp[dp.length - 1][1] = 1;
        for (int i = 1; i < nums.length; i++) {
            dp[i][0] = dp[i - 1][0] * nums[i - 1];
            dp[dp.length - 1 - i][1] = dp[dp.length - i][1] * nums[dp.length - i];
        }
        int[] result = new int[nums.length];
        result[0] = dp[0][1];
        result[result.length - 1] = dp[dp.length - 1][0];
        for (int i = 1; i < nums.length - 1; i++) {
            result[i] = dp[i][0] * dp[i][1];
        }
        return result;
    }
}
